package com.zf.poi.excel.controller;

import com.zf.common.core.result.RestResponse;
import com.zf.poi.excel.entity.Student;
import com.zf.poi.excel.utils.CellReadUtils;
import com.zf.poi.excel.utils.ExcelUtils;
import com.zf.poi.excel.utils.ExcelWriteUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

/**
 * @author Zhou Feng
 */
@RestController
@RequestMapping("/excel")
public class ExcelController {


    /**
     * 导入 Excel
     */
    @PostMapping("/import")
    public RestResponse<?> importExcel(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        BufferedInputStream inputStream = new BufferedInputStream(multipartFile.getInputStream());
        String realExtension = ExcelUtils.getExtensionByFileMagic(inputStream);
        if (!ExcelUtils.EXCEL_EXTENSION_SET.contains(realExtension)) {
            return RestResponse.failed("不是excel文件");
        }
        readExcel(inputStream);
        return RestResponse.success();
    }

    /**
     * 导出Excel
     */
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) {
        ArrayList<Student> data = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Student student = new Student();
            student.setStudentName("学生" + i);
            student.setClassName("班级" + i);
            student.setAge(15 + i % 2);
            data.add(student);
        }
        ExcelWriteUtils.exportExcel(response, "导出测试数据", Student.class, data);
    }

    public static void readExcel(InputStream inputStream) throws IOException {
        // 读取 excel 数据
        Workbook workbook = WorkbookFactory.create(inputStream);
        // 获取第 0 张表
        Sheet sheet = workbook.getSheetAt(0);
        // 获取所有行数
        int rowCount = sheet.getPhysicalNumberOfRows();
        for (int i = 0; i < rowCount; i++) {
            // 获取一行
            Row row = sheet.getRow(i);
            // 改行的总列数
            int columnCount = row.getPhysicalNumberOfCells();
            for (int j = 0; j < columnCount; j++) {
                // 获取一个单元格, 如果该单元格是和其他单元格合并而成的,那么只有左上角的单元格可以获取到值
                Cell cell = row.getCell(j);
                System.out.print(CellReadUtils.getCellDataStr(cell, null) + ", ");
            }
            System.out.println();
        }
    }
}
